package com.gsbelarus.gedemin.salary.fragment.gdmsg;

import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.gsbelarus.gedemin.lib.sync.protocol.SyncServiceModel;
import com.gsbelarus.gedemin.lib.sync.protocol.entity.SyncServiceTask;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.SyncActivityDrawerModel;
import com.gsbelarus.gedemin.lib.ui.fragment.FragmentModel;
import com.gsbelarus.gedemin.salary.App;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.activity.GdMsgDetailPager;
import com.gsbelarus.gedemin.salary.activity.GdMsgNew;
import com.gsbelarus.gedemin.salary.activity.Main;
import com.gsbelarus.gedemin.salary.adapter.GdMsgRecyclerViewAdapter;
import com.gsbelarus.gedemin.salary.database.RealmHelper;
import com.gsbelarus.gedemin.salary.entity.SyncRequestType;
import com.gsbelarus.gedemin.salary.entity.model.GdMsgModel;
import com.gsbelarus.gedemin.salary.service.SendMsgDataService;
import com.gsbelarus.gedemin.salary.service.SyncService;
import com.gsbelarus.gedemin.salary.ui.DividerItemDecoration;
import com.gsbelarus.gedemin.salary.ui.EmptyRecyclerView;
import com.melnykov.fab.FloatingActionButton;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nispok.snackbar.listeners.ActionClickListener;
import com.nispok.snackbar.listeners.EventListener;

import java.lang.reflect.Field;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;

public class GdMsgsListFragment extends FragmentModel implements ActionMode.Callback,
        GdMsgRecyclerViewAdapter.OnItemListener,
        View.OnClickListener,
        View.OnKeyListener,
        RealmChangeListener {

    private static final String TABLET_VIEWPAGER_FRAGMENT = "tablet_viewpager_fragment";
    public static final String TAG_GD_MSG_ID = "tag_gd_msg_id";
    public static final String TAG_TEXT_FILTER = "tag_text_filter";
    public static final String TAG_SENDER_FILTER = "tag_sender_filter";

    private GdMsgRecyclerViewAdapter recyclerAdapter;
    private EmptyRecyclerView recyclerView;
    private RecyclerView.OnScrollListener scrollListener;
    private SwipeRefreshLayout swipeRefreshLayout;
    private FloatingActionButton fab;
    private Spinner mGdMsgFilterSpinner;
    private SearchView searchView;
    private BroadcastReceiver receiver;

    private boolean isTwoPaneGdMsg = false;
    private boolean isItemsDelete;

    private ActionMode actionMode;

    private RealmHelper realmHelper;
    private RealmResults<GdMsgModel> gdMsgModels;

    /**
     * @return id View для отрисовки в фрагменте
     */
    @Override
    public int getViewResource() {
        return R.layout.gdmsgs_list_fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSyncActivity().showElevationToolbar(true);
        Toolbar toolbar = getSyncActivity().getToolbar();

        realmHelper = new RealmHelper(Realm.getInstance(context));

        gdMsgModels = realmHelper.getAllGdMsgs();
        recyclerAdapter = new GdMsgRecyclerViewAdapter(context, gdMsgModels);

        mGdMsgFilterSpinner = (Spinner) LayoutInflater.from(getActivity()).inflate(R.layout.gdmsgs_spinner, toolbar, false);

        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getSyncActivity().getToolbar().getContext(),
                R.array.title_msg_filter, R.layout.gdmsgs_spinner_drop_title);
        adapter.setDropDownViewResource(R.layout.gdmsgs_spinner_drop_list);
        mGdMsgFilterSpinner.setAdapter(adapter);

        mGdMsgFilterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long itemId) {
                switch (position) {
                    case 0:
                        recyclerAdapter.setSenderFilter(null);
                        break;
                    case 1:
                        recyclerAdapter.setSenderFilter(GdMsgModel.Sender.SERVER);
                        break;
                    case 2:
                        recyclerAdapter.setSenderFilter(GdMsgModel.Sender.CLIENT);
                        break;
                    default:
                        recyclerAdapter.setSenderFilter(null);
                        break;
                }
                recyclerAdapter.notifyDataSetChangedWithFilters();
                updateDetailFragment(recyclerAdapter.getSenderFilter(), recyclerAdapter.getTextFilter());
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        realmHelper.getRealm().addChangeListener(this);
        createBroadcast();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        realmHelper.getRealm().removeChangeListener(this);
        realmHelper.getRealm().close();
        recyclerView.removeOnScrollListener(scrollListener);
        getActivity().unregisterReceiver(receiver);
    }

    /**
     * Вызывается при создании View или при смене ориентации экрана.
     * Может быть переопределен в классе наследнике
     *
     * @param rootView корневое View
     */
    @Override
    public void onCreateViewFragment(View rootView) {
        super.onCreateViewFragment(rootView);

        setHasOptionsMenu(true);

        FrameLayout fragmentItemDetail = (FrameLayout) getActivity().findViewById(R.id.flGdMsgDetailContainer);
        if (fragmentItemDetail != null) { // Configuration.SCREENLAYOUT_SIZE_LARGE

            openDetailFragment(gdMsgModels.isEmpty() ? -1 : gdMsgModels.first().getUid());

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
            LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.mail_content);
            layout.setLayoutParams(params);

            isTwoPaneGdMsg = true;
        }

        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
        recyclerView = (EmptyRecyclerView) rootView.findViewById(R.id.recycler_view);
        recyclerView.setAdapter(recyclerAdapter);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        recyclerView.setEmptyView(rootView.findViewById(R.id.empty_rec_view));
        recyclerAdapter.setOnItemClickListener(this);

        // костыль, отключает swipeRefresh если список может скролиться вверх
        recyclerView.removeOnScrollListener(scrollListener);
        recyclerView.addOnScrollListener(scrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int topRowVerticalPosition = (recyclerView == null ||
                        recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);
            }
        });

        fab = (FloatingActionButton) rootView.findViewById(R.id.fab_add);
        fab.attachToRecyclerView(recyclerView);
        fab.setOnClickListener(this);

        swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getActivity().startService(SyncServiceModel.getIntentWithTask(new Intent(getActivity(), SyncService.class),
                        SyncServiceTask.TypeOfTask.SERIES_SYNC, new SyncRequestType(SyncRequestType.TypeOfRequest.MSG_REQUEST)));
            }
        });
    }

    private void openDetailFragment(int gdMsgId) {
        GdMsgDetailPagerFragment fragment = (GdMsgDetailPagerFragment) getActivity().getSupportFragmentManager().findFragmentByTag(TABLET_VIEWPAGER_FRAGMENT);

        if (fragment == null) {
            FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

            fragment = GdMsgDetailPagerFragment.newInstance();
            fragment.setGdMsgId(gdMsgId);
            fragment.setTextFilter(recyclerAdapter.getTextFilter());
            fragment.setSenderFilter(recyclerAdapter.getSenderFilter());

            fragmentTransaction.add(R.id.flGdMsgDetailContainer, fragment, TABLET_VIEWPAGER_FRAGMENT);
            fragmentTransaction.commitAllowingStateLoss();
        } else {
            fragment.setGdMsgId(gdMsgId);
            fragment.setTextFilter(recyclerAdapter.getTextFilter());
            fragment.setSenderFilter(recyclerAdapter.getSenderFilter());
            fragment.reloadFragmentData();
        }
    }

    private void updateDetailFragment(GdMsgModel.Sender senderFilter, String filter) {
        GdMsgDetailPagerFragment fragment = (GdMsgDetailPagerFragment) getActivity()
                .getSupportFragmentManager().findFragmentByTag(TABLET_VIEWPAGER_FRAGMENT);
        if (fragment != null) {
            fragment.setTextFilter(filter);
            fragment.setSenderFilter(senderFilter);
            fragment.reloadFragmentData();
        }
    }

    /**
     * Чтение данных из БД в новом потоке
     */
    @Override
    public void readDataBase() {

    }

    /**
     * Метод вызывается после чтения данных из БД или при смене ориентации экрана.
     * Может быть вызван до окончания выполнения потока для запроса данных из БД, поэтому следует проверять данные на null.
     * Служит для инициализации View данными
     *
     * @param rootView корневое View
     */
    @Override
    public void initView(View rootView) {
        swipeRefreshLayout.setRefreshing(false);
        recyclerAdapter.notifyDataSetChanged();
        updateDetailFragment(recyclerAdapter.getSenderFilter(), recyclerAdapter.getTextFilter());
    }

    private void myToggleSelection(int idx) {
        recyclerAdapter.toggleSelection(idx);
        String title = getString(R.string.selected_count, recyclerAdapter.getSelectedItemCount());
        actionMode.setTitle(title);
    }

    private void checked(View view, final int position) {
        int duration = 100;
        View animView = view.findViewById(R.id.image_view_avatar);

        ObjectAnimator objectAnimatorStart = ObjectAnimator.ofFloat(animView, "scaleX", 1f, 0f).setDuration(duration);
        final ObjectAnimator objectAnimatorFinish = ObjectAnimator.ofFloat(animView, "scaleX", 0f, 1f).setDuration(duration);
        objectAnimatorStart.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                myToggleSelection(position);
                objectAnimatorFinish.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        objectAnimatorStart.start();
    }

    @Override
    public void onItemClick(View v, int position) {
        if (actionMode != null) {
            checked(v, position);
        } else {
            SnackbarManager.dismiss();
            GdMsgModel gdMsgModel = recyclerAdapter.getItem(position);

            FrameLayout fragmentItemDetail = (FrameLayout) getActivity().findViewById(R.id.flGdMsgDetailContainer);
            if (fragmentItemDetail != null && isTwoPaneGdMsg) {
                openDetailFragment(gdMsgModel.getUid());
            } else {
                Intent i = new Intent(getActivity(), GdMsgDetailPager.class);
                Bundle bundle = new Bundle();
                bundle.putInt(TAG_GD_MSG_ID, gdMsgModel.getUid());
                bundle.putString(TAG_TEXT_FILTER, recyclerAdapter.getTextFilter());
                bundle.putSerializable(TAG_SENDER_FILTER, recyclerAdapter.getSenderFilter());
                i.putExtras(bundle);
                startActivity(i);
            }
        }
    }

    @Override
    public boolean onItemLongClick(View v, int position) {
        if (actionMode != null) return false;
        actionMode = getSyncActivity().getToolbar().startActionMode(GdMsgsListFragment.this);
        checked(v, position);
        return true;
    }

    //implements View.OnClickListener
    @Override
    public void onClick(View view) {
        if (view == null) return;

        if (view.getId() == R.id.fab_add) {
            new MaterialDialog.Builder(getActivity())
                    .title(R.string.new_msg)
                    .items(R.array.new_msg_subjects)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                            Intent i = new Intent(getActivity(), GdMsgNew.class);
                            switch (which) {
                                case 0:
                                    i.putExtra("gdMsgType", GdMsgModel.Subject.INCOME);
                                    break;
                                case 1:
                                    i.putExtra("gdMsgType", GdMsgModel.Subject.VACATION);
                                    break;
                                case 2:
                                    i.putExtra("gdMsgType", GdMsgModel.Subject.HOLIDAY);
                                    break;
                            }
                            startActivity(i);
                        }
                    })
                    .show();
        }
    }

    //implements ActionMode.Callback
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        getActivity().getMenuInflater().inflate(R.menu.gdmsgs_action, menu);
        fab.setVisibility(View.GONE);
        getSyncActivity().getToolbar().setVisibility(View.INVISIBLE);
        getSyncActivity().getDrawer().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        SnackbarManager.dismiss();
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_delete:

                SnackbarManager.dismiss();
                final List<Integer> selectedItemsUid = recyclerAdapter.getSelectedItems();

                SnackbarManager.show(
                        Snackbar.with(getActivity())
                                .text(getResources().getString(R.string.msgs_removed, selectedItemsUid.size()))
                                .actionLabel(getResources().getString(R.string.action_undo))
                                .actionColor(getResources().getColor(R.color.blue))
                                .duration(Snackbar.SnackbarDuration.LENGTH_LONG)
                                .attachToRecyclerView(recyclerView)
                                .actionListener(new ActionClickListener() {
                                    @Override
                                    public void onActionClicked(Snackbar snackbar) {
                                        isItemsDelete = false;
                                        realmHelper.getRealm().cancelTransaction();
                                        recyclerAdapter.notifyDataSetChanged();
                                        updateDetailFragment(recyclerAdapter.getSenderFilter(), recyclerAdapter.getTextFilter());
                                    }
                                })
                                .eventListener(new EventListener() {
                                    @Override
                                    public void onShow(Snackbar snackbar) {
                                        isItemsDelete = true;
                                        realmHelper.getRealm().beginTransaction();
                                        for (Integer uid : selectedItemsUid)
                                            startDeleteByUid(uid);
                                        recyclerAdapter.notifyDataSetChanged();
                                        updateDetailFragment(recyclerAdapter.getSenderFilter(), recyclerAdapter.getTextFilter());

                                        actionMode.finish();
                                    }

                                    @Override
                                    public void onShowByReplace(Snackbar snackbar) {
                                    }

                                    @Override
                                    public void onShown(Snackbar snackbar) {
                                    }

                                    @Override
                                    public void onDismiss(Snackbar snackbar) {
                                        if (isItemsDelete) {
                                            isItemsDelete = false;
                                            realmHelper.getRealm().commitTransaction();
                                        }
                                    }

                                    @Override
                                    public void onDismissByReplace(Snackbar snackbar) {
                                    }

                                    @Override
                                    public void onDismissed(Snackbar snackbar) {
                                    }
                                }));
                return true;
            case R.id.menu_select_all:
                for (int i = 0; i < recyclerAdapter.getItemCount(); i++) {
                    recyclerAdapter.setSelection(i);
                }
                String title = getString(R.string.selected_count, recyclerAdapter.getSelectedItemCount());
                actionMode.setTitle(title);
                return true;
            default:
                return false;
        }
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        this.actionMode = null;
        recyclerAdapter.clearSelections();
        fab.setVisibility(View.VISIBLE);
        getSyncActivity().getToolbar().setVisibility(View.VISIBLE);
        getSyncActivity().getDrawer().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }

    private void startDeleteByUid(int uid) {
        try {
            GdMsgModel gdMsg = realmHelper.getRealm()
                    .where(GdMsgModel.class).equalTo("uid", uid)
                    .findFirst();
            if (gdMsg != null)
                realmHelper.deleteGdMsgWithSync(gdMsg, false);
        } catch (Exception ex) {
            //Crashlytics.getInstance().core.logException(ex);
            Log.e("my", "startDeleteByUid " + ex.getMessage());
        }
    }

    // implements View.OnKeyListener
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!searchView.isIconified()) {
                closeAndClearSearch();
                animateToggle(1f, 0f);
                return true;
            }
        }
        return false;
    }

    /**
     * вызывается при изменении базы из потока UI
     */
    @Override
    public void onChange() {
        recyclerAdapter.notifyDataSetChanged();
        ((Main) getActivity()).updateMailCounter();
        updateDetailFragment(recyclerAdapter.getSenderFilter(), recyclerAdapter.getTextFilter());
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getSyncActivity() != null) {
            if (getSyncActivity().getSupportActionBar() != null)
                getSyncActivity().getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSyncActivity().getToolbar().addView(mGdMsgFilterSpinner);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (getSyncActivity() != null) {
            if (getSyncActivity().getSupportActionBar() != null)
                getSyncActivity().getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSyncActivity().getToolbar().removeView(mGdMsgFilterSpinner);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.gdmsgs, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setImeOptions(EditorInfo.IME_ACTION_UNSPECIFIED);
        searchView.setLayoutParams(new SearchView.LayoutParams(SearchView.LayoutParams.MATCH_PARENT,
                SearchView.LayoutParams.MATCH_PARENT));
        searchView.requestLayout();
        searchView.setMaxWidth(10000);

        /** убираем иконку из hint */
        SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete)
                searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
        SpannableStringBuilder ssb = new SpannableStringBuilder("");
        ssb.append(getResources().getString(R.string.msg_search_placeholder));
        searchAutoComplete.setHint(ssb);

        try {
            /** меняем курсор */
            Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
            f.setAccessible(true);
            f.set(searchAutoComplete, R.drawable.edittext_cursor_white);
        } catch (Exception ignored) {
        }

        /** убираем полосу снизу */
        View searchPlate = searchView.findViewById(android.support.v7.appcompat.R.id.search_plate);
        searchPlate.setBackgroundColor(Color.TRANSPARENT);

        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGdMsgFilterSpinner != null)
                    mGdMsgFilterSpinner.setVisibility(View.GONE);
                animateToggle(0f, 1f);
                getSyncActivity().getDrawer().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }
        });

        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                if (mGdMsgFilterSpinner != null)
                    mGdMsgFilterSpinner.setVisibility(View.VISIBLE);
                animateToggle(1f, 0f);
                getSyncActivity().getDrawer().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

                recyclerAdapter.setTextFilter(null);
                recyclerAdapter.notifyDataSetChangedWithFilters();
                updateDetailFragment(recyclerAdapter.getSenderFilter(), recyclerAdapter.getTextFilter());
                return false;
            }
        });

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                recyclerAdapter.setTextFilter(s);
                recyclerAdapter.notifyDataSetChangedWithFilters();
                updateDetailFragment(recyclerAdapter.getSenderFilter(), recyclerAdapter.getTextFilter());

                return true;
            }
        });
    }

    private void animateToggle(float start, float end) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            ValueAnimator offsetAnimator = ValueAnimator.ofFloat(start, end);
            offsetAnimator.setDuration(300);
            offsetAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
            offsetAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float offset = (Float) animation.getAnimatedValue();
                    getSyncActivity().getDrawerToggle().onDrawerSlide(null, offset);
                }
            });
            offsetAnimator.start();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (!searchView.isIconified()) {
                    closeAndClearSearch();
                    animateToggle(1f, 0f);
                    return false;
                }
                /** т.к действие по кнопке home переопределено, следует "руками" открыть/закрыть drawer */
                if (getSyncActivity().getDrawer().isDrawerOpen(GravityCompat.START))
                    getSyncActivity().getDrawer().closeDrawers();
                else
                    getSyncActivity().getDrawer().openDrawer(GravityCompat.START);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void closeAndClearSearch() {
        if (searchView != null) {
            /** чистим и скрываем поле поиска */
            searchView.setQuery("", true);
            searchView.setIconified(true);
        }
    }

    private SyncActivityDrawerModel getSyncActivity() {
        return (SyncActivityDrawerModel) getActivity();
    }

    @Override
    public void onPause() {
        super.onPause();
        SnackbarManager.dismiss();
    }

    @Override
    public void onResume() {
        super.onResume();
        Tracker tracker = ((App) getActivity().getApplication()).getTracker(App.TrackerName.APP_TRACKER);
        tracker.setScreenName(getClass().getSimpleName());
        tracker.send(new HitBuilders.AppViewBuilder().build());
    }

    /**
     * ловим уведомление об успешной отправке сообщения.
     * BroadcastReceiver регистрируется в onCreate(), удаляется в onDestroy()
     */
    private void createBroadcast() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("intent", intent.toString());
                if (intent.getExtras().getBoolean(SendMsgDataService.EXTRA_KEY_GD_MSG_WAS_SENT, false)) {
                    realmHelper.getRealm().refresh();
                    recyclerAdapter.notifyDataSetChanged();
                }
            }
        };
        IntentFilter intFilt = new IntentFilter(SendMsgDataService.SEND_GD_MSG_BROADCAST_ACTION);
        getActivity().registerReceiver(receiver, intFilt);
    }
}
